package com.nd.fastdp.org.dao;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nd.fastdp.db.mybatis.wrapper.QueryWrapperX;
import com.nd.fastdp.framework.pojo.bo.LoginUser;
import com.nd.fastdp.framework.pojo.bo.LoginUserDataScope;
import com.nd.fastdp.framework.pojo.bo.LoginUserMangDept;
import com.nd.fastdp.framework.pojo.constant.CoreStatusEnum;
import com.nd.fastdp.framework.pojo.constant.DataScopeEnum;
import com.nd.fastdp.framework.pojo.constant.DelStatusEnum;
import com.nd.fastdp.framework.pojo.constant.StatusEnum;
import com.nd.fastdp.framework.pojo.dto.DelParam;
import com.nd.fastdp.framework.pojo.dto.StateParam;
import com.nd.fastdp.org.model.dto.user.UserListParam;
import com.nd.fastdp.org.model.dto.user.UserQueryParam;
import com.nd.fastdp.org.model.entity.Role;
import com.nd.fastdp.org.model.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Repository
public interface UserMapper extends BaseMapper<User> {

    String MODULE_CODE = "USER_MANG";

    @SuppressWarnings("deprecation")
    default User getByCode(@Param("code") String code) {

        return selectOne(new QueryWrapper<User>().eq("code", code).eq("del", DelStatusEnum.NORMAL.getValue()));
    }

    default boolean isExist(String code) {

        User user = selectOne(new QueryWrapper<User>().eq("del", DelStatusEnum.NORMAL.getValue())
                .eq("code", code));

        return user != null;
    }

    default boolean isExist(String id, String code) {

        User user = selectOne(new QueryWrapper<User>().eq("del", DelStatusEnum.NORMAL.getValue())
                .ne("id", id)
                .eq("code", code));

        return user != null;
    }

    List<User> findByRoleId(@Param("roleId") String roleId);

    default List<User> listAllEnable() {

        return selectList(new QueryWrapper<User>().eq("del", DelStatusEnum.NORMAL.getValue())
                .eq("state", StatusEnum.ENABLE.getValue())
                .ne("fdp_core", CoreStatusEnum.YES.getValue())
                .orderByAsc("sort"));
    }

    default List<User> listAll() {

        return selectList(new QueryWrapper<User>().eq("del", DelStatusEnum.NORMAL.getValue()).ne("fdp_core", CoreStatusEnum.YES.getValue()).orderByAsc("sort"));
    }

    default List<User> list(UserListParam param) {
        return selectList(queryWrapper(param));
    }

    default IPage<User> page(IPage<User> page, UserQueryParam param) {
        return selectPage(page, queryWrapper(param));
    }

    default QueryWrapper queryWrapper(UserListParam param){

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("del", DelStatusEnum.NORMAL.getValue())
                .like(StringUtils.isNotEmpty(param.getCode()), "code", param.getCode())
                .eq(StringUtils.isNotEmpty(param.getDept()), "dept", param.getDept())
                .eq(StringUtils.isNotEmpty(param.getPosition()), "employee_position", param.getPosition())
                .eq(null != param.getState(), "state", param.getState())
                .ne("fdp_core", CoreStatusEnum.YES.getValue())
                .orderByAsc("sort");

        if(StringUtils.isNotEmpty(param.getName())){

            queryWrapper.and(new Consumer<QueryWrapper<User>>() {

                @Override
                public void accept(QueryWrapper<User> queryWrapper) {
                    queryWrapper.like(StringUtils.isNotEmpty(param.getName()), "name", param.getName());
                    queryWrapper.or();
                    queryWrapper.like(StringUtils.isNotEmpty(param.getName()), "code", param.getName());
                }
            });
        }

        fullQuerytDataScope(param.getLoginUser(), queryWrapper);

        return queryWrapper;
    }

    default void fullQuerytDataScope(LoginUser loginUser, QueryWrapper queryWrapper) {

        if (null != loginUser) {
            Integer dataScope = null;
            HashMap<String, LoginUserDataScope> dataScopeMap = loginUser.getDataScopeMap();
            LoginUserDataScope loginUserDataScope = dataScopeMap.get(MODULE_CODE);
            if (null == loginUserDataScope) {
                return;
            }
            String dataScopeStr = loginUserDataScope.getCode();
            if (dataScopeStr != null) {
                try {
                    dataScope = Integer.parseInt(dataScopeStr);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }

                int dataScopeBase = dataScope.intValue();

                if (DataScopeEnum.ALL.getValue().intValue() == dataScopeBase) {

                } else if (DataScopeEnum.SELF_MANGE_AREA.getValue().intValue() == dataScopeBase) {


                } else if (DataScopeEnum.SELF_MANGE_DEPT.getValue().intValue() == dataScopeBase) {
                    // 管理额区域
                    // 获取管理的部门id
                    List<LoginUserMangDept> managerDept = loginUser.getDepts();
                    List<String> deptCodeList = managerDept.stream().map(v -> v.getId()).collect(Collectors.toList());
                    if (deptCodeList.isEmpty()) {
                        queryWrapper.eq("1", "2");
                    } else {
                        queryWrapper.in("dept", deptCodeList);
                    }

                } else if (DataScopeEnum.SELF_DEPT.getValue().intValue() == dataScopeBase) {

                    queryWrapper.in("dept", loginUser.getDept());
                } else if (DataScopeEnum.SELF.getValue().intValue() == dataScopeBase) {

                    queryWrapper.in("id", loginUser.getUserId());
                }
            }
        }
    }

    default void del(DelParam param) {

        User user = null;
        for (String id : param.getIds()) {

            user = new User();

            user.setId(id);
            user.init(param);
            user.setDel(DelStatusEnum.DEL.getValue());

            updateById(user);
        }
    }

    default void updateState(StateParam param) {

        User user = null;
        for (String id : param.getIds()) {

            user = new User();

            user.setId(id);
            user.init(param);
            user.setState(param.getState());

            updateById(user);
        }
    }

}
